<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区 -->
      <el-alert
        show-icon
        title="注意:只允许为第三季分类设置相关参数"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>商品分类：</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="{
              value: 'cat_id',
              label: 'cat_name',
              children: 'children'
            }"
            @change="handleChange"
            :show-all-levels="false"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scoped">
                <el-tag
                  v-for="(item, i) in scoped.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scoped.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag input-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scoped">
                <el-button
                  size="mini"
                  type="primary"
                  @click="showEditDialog(scoped.row.attr_id)"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            :disabled="isBtnDisabled"
            >静态属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableData" border stripe>
           <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scoped">
                <el-tag
                  v-for="(item, i) in scoped.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scoped.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag input-new-tag"
                  size="small"
                  @click="showInput"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scoped">
                <el-button
                  size="mini"
                  type="primary"
                  @click="showEditDialog(scoped.row.attr_id)"
                  icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button size="mini" type="danger" icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + this.titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogVisibleClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <!-- 添加参数的对话框 -->
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      :title="'添加' + this.titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogVisibleClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <!-- 添加参数的对话框 -->
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框选中的id
      selectedCateKeys: [],
      /* 被激活页签的名称 */
      activeName: 'many',
      /* 动态参数数据 */
      manyTableData: [],
      /* 静态参数数据 */
      onlyTableData: [],
      /* 控制对话框是否显示 */
      addDialogVisible: false,
      /* 控制编辑对话框是否显示 */
      editDialogVisible: false,
      /* 添加参数表单 */
      addForm: {
        attr_name: ''
      },
      /* 表单验证对象 */
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      /* 修改表单 */
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      /* 修改表单校验 */
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      /* 控制文本框和按钮的显示 */
      inputVisible: false,
      /* 文本框输入的内容 */
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    isBtnDisabled() {
      /* 没有选中三级分类,按钮被禁用返回true，否则返回false */
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    /* 返回当前三级分类id */
    catId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2] * 1
      } else {
        return null
      }
    },
    /* 动态计算对应文本 */
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    /* 获取商品分类数据 */
    async getCateList() {
      const { data: res } = await this.$http.get(`categories`)
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类数据失败!')
      }
      this.cateList = res.data
      console.log('商品分类数据', this.cateList)
    },
    /* 当选中节点变化时触发 */
    async handleChange() {
      this.getParamsData()
    },
    /* 级联选择器  与 tab标签 改动共用方法*/
    async getParamsData() {
      // 证明选中的不是三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 选中的是三级分类
      console.log(this.selectedCateKeys)
      // 请求参数列表
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败!')
      }
      /* 以空格进行拆分 */
      res.data.forEach(item => {
        /* 控制文本框的显示和隐藏 */
        // this.inputVisible = false
        /* 文本框输入值 */
        // this.inputValue = ''
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      console.log('参数列表数据', res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
    },
    /* tab 被选中时触发 */
    handleTabClick() {
      this.getParamsData()
    },
    /* 监听对话框关闭事件 */
    addDialogVisibleClosed() {
      this.$refs.addFormRef.resetFields()
    },
    /* 点击按钮 添加参数 */
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return null
        const { data: res } = await this.$http.post(
          `categories/${this.catId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    /* 编辑 对话框关闭回调 */
    editDialogVisibleClosed() {
      this.$refs.editFormRef.resetFields
    },
    /* 点击按钮 展示编辑对话框 */
    async showEditDialog(attrId) {
      // 查询当前参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取参数信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    /* 点击按钮，编辑信息 */
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.catId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数信息失败！')
        }
        this.$message.success('修改参数信息成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    /* 文本框失去了焦点，或摁下了 Enter 都会触发 */
    async handleInputConfirm(row) {
      /* 防止输入空格 */
      if (this.inputValue.trim().length === 0) {
        this.inputVisible = false
        this.inputValue = ''
        return
      }
      /* 如果没有return 则证明输入的内容，需要做后续处理 */
      row.attr_vals.push(this.inputValue.trim()) // 要添加的值保存到数组中
      this.inputValue = ''
      this.inputVisible = false
      // 保存信息
      this.saveAttrVals(row)
    },
    /* 对 attr_vals 的操作保存到数据库 */
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.catId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('修改参数信息失败!')
      }
      this.$message.success('修改参数信息成功!')
    },
    /* 显示文本框 */
    showInput() {
      this.inputVisible = true
      /* nextTick 方法作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码 */
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /* 删除对应参数可选项 */
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 10px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>